package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.dto.NursingTaskCancleDto;
import com.zzyl.nursing.dto.NursingTaskDoDto;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.INursingTaskService;
import com.zzyl.nursing.vo.NursingTaskVO;
import com.zzyl.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 护理任务Service业务层处理
 */
@Service
@Slf4j
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper,NursingTask> implements INursingTaskService
{
    @Autowired
    private NursingTaskMapper nursingTaskMapper;
    @Autowired
    private IElderService elderService;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTask selectNursingTaskById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询护理任务列表
     *
     * @param nursingTask 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTask> selectNursingTaskList(NursingTask nursingTask)
    {
        return nursingTaskMapper.selectNursingTaskList(nursingTask);
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask)
    {
        return save(nursingTask)?1:0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask)
    {
        return updateById(nursingTask)?1:0;
    }

    /*取消任务*/
    @Override
    public void cancel(NursingTaskCancleDto nursingTaskCancleDto) {
        NursingTask nursingTask = new NursingTask();
        nursingTask.setId(Long.valueOf(nursingTaskCancleDto.getTaskId()));
        nursingTask.setCancelReason(nursingTaskCancleDto.getReason());
        nursingTask.setStatus(3);
        nursingTaskMapper.updateNursingTask(nursingTask);
    }

    /*任务执行*/
    @Override
    public void doTask(NursingTaskDoDto nursingTaskDoDto) {
        NursingTask nursingTask = new NursingTask();
        //设置nursingtaskid
        nursingTask.setId(Long.valueOf(nursingTaskDoDto.getTaskId()));
        nursingTask.setStatus(2);
        nursingTask.setMark(nursingTaskDoDto.getMark());
        nursingTask.setTaskImage(nursingTaskDoDto.getTaskImage());
        nursingTask.setRealServerTime(DateUtil.parse(nursingTaskDoDto.getEstimatedServerTime()).toLocalDateTime());

        nursingTaskMapper.updateNursingTask(nursingTask);
    }

    /*任务改期*/
    @Override
    public void updateDoTaskTime(NursingTaskDoDto nursingTaskDoDto) {
        NursingTask nursingTask = new NursingTask();
        //设置nursingtaskid
        nursingTask.setId(Long.valueOf(nursingTaskDoDto.getTaskId()));
        nursingTask.setEstimatedServerTime(DateUtil.parse(nursingTaskDoDto.getEstimatedServerTime()).toLocalDateTime());
        nursingTaskMapper.updateNursingTask(nursingTask);
    }


    @Autowired
    private ICheckInService checkInService;
    /**
     * 查看任务详情
     * @param id
     * @return
     */
    @Override
    public NursingTaskVO getInfo(Long id) {
        NursingTask nursingTask = nursingTaskMapper.selectNursingTaskById(id);
        if (nursingTask == null) {
            throw new RuntimeException("Nursing task not found with id: " + id);
        }

        Elder elder = elderService.getById(nursingTask.getElderId());
        if (elder == null) {
            throw new RuntimeException("Elder not found with id: " + nursingTask.getElderId());
        }

        NursingTaskVO nursingTaskVO = new NursingTaskVO();

        // 计算老人年龄
        String birthDateStr = elder.getIdCardNo().substring(6, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
        LocalDate now = LocalDate.now();
        Integer age = Period.between(birthDate, now).getYears();

        // 获取护理员姓名
        String nursingId = nursingTask.getNursingId();
        List<Integer> idList = Arrays.stream(nursingId.split(","))
                .map(String::trim)
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", idList).select("nick_name");
        List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapper);

        // 提取姓名字段
        List<String> userNickNames = sysUsers.stream()
                .map(SysUser::getNickName) // 获取每个用户的姓名
                .collect(Collectors.toList());

        BeanUtil.copyProperties(elder, nursingTaskVO);
        BeanUtil.copyProperties(nursingTask, nursingTaskVO);
        // 获取护理等级 从checkin中获取
        nursingTaskVO.setNursingLevelName(checkInService.selectNursingLevelByElderId(elder.getId()));

//        //填充创建者
//       nursingTaskVO.setCreateBy(sysUserMapper.getNickNameByProjectId(Integer.valueOf(nursingTask.getCreateBy())));

       //对执行的任务进行判断
        if (nursingTaskVO.getStatus() == 1){
            nursingTaskVO.setUpdateTime(null);
            nursingTaskVO.setUpdater(null);
        }
        if(nursingTaskVO.getStatus() == 2){
            nursingTaskVO.setUpdateTime(null);
        }
        //填充执行人
        if (nursingTaskVO.getStatus() == 2 || nursingTaskVO.getStatus() ==3  ){
            nursingTaskVO.setUpdater(sysUserMapper.getUpdatName(Integer.valueOf(nursingTask.getUpdateBy())));
        }

        nursingTaskVO.setAge(age);
        nursingTaskVO.setNursingName(userNickNames);
        return nursingTaskVO;
    }


    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id)
    {
        return removeById(id)?1:0;
    }
}
